package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 捕获运行时异常
     * @param ex
     * @return
    public class SQLIntegrityConstraintViolationException extends SQLNonTransientException {
     *
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();// 获取异常信息
        if (message.contains("Duplicate entry")){// 判断异常信息中是否包含 Duplicate entry
            String[] split = message.split(" ");// 获取用户名
            String username = split[2];// 获取用户名
            String msg = username+ MessageConstant.ALREADY_EXISTS;// 拼接异常信息
            return Result.error(msg);// 返回错误结果
        }else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);// 返回错误结果
        }
    }

    @ExceptionHandler
    public Result exceptionHandler(RuntimeException ex){
        String message = ex.getMessage();
        if (message.contains("当前分类下关联了菜品")){
            log.error("异常信息：{}", ex.getMessage());
            return Result.error(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }
}
